//
// Created by jc on 17-8-7.
//

#include <jni.h>
#include <string>
#include <android/log.h>

#define info(tag, msg) __android_log_write(ANDROID_LOG_DEBUG, tag, msg)

extern "C"
JNIEXPORT jstring JNICALL
Java_com_jc_cm_Lost_test(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from test C++";
    return env->NewStringUTF(hello.c_str());
}

void print(JNIEnv *env, jclass thiz) {
    info("cm", "Hello, I am from C++");
}

static JNINativeMethod METHODS[]= {
        {"print", "()V", (void *)print}
};

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    int ret = -1;
    JNIEnv *env;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) == JNI_OK) {
        info("cm", "Use JNI_VERSION_1_6");
        jclass clazz = env->FindClass("com/jc/cm/Lost");
        if (clazz != NULL) {
            if (env->RegisterNatives(clazz, METHODS, sizeof(METHODS) / sizeof(METHODS[0])) >= 0) {
                ret = JNI_VERSION_1_6;
            }
            env->DeleteLocalRef(clazz);
        }
    } else if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) == JNI_OK) {
        info("cm", "Use JNI_VERSION_1_4");
        jclass clazz = env->FindClass("com/jc/cm/Lost");
        if (clazz != NULL) {
            if (env->RegisterNatives(clazz, METHODS, sizeof(METHODS) / sizeof(METHODS[0])) >= 0) {
                ret = JNI_VERSION_1_4;
            }
            env->DeleteLocalRef(clazz);
        }
    }
    return ret;
}

JNIEXPORT void JNI_OnUnload(JavaVM* vm, void* reserved) {
    JNIEnv *env;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) == JNI_OK) {
        info("cm", "Use JNI_VERSION_1_6");
        jclass clazz = env->FindClass("com/jc/cm/Lost");
        if (clazz != NULL) {
            env->UnregisterNatives(clazz);
            env->DeleteLocalRef(clazz);
        }
    } else if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) == JNI_OK) {
        info("cm", "Use JNI_VERSION_1_4");
        jclass clazz = env->FindClass("com/jc/cm/Lost");
        if (clazz != NULL) {
            env->UnregisterNatives(clazz);
            env->DeleteLocalRef(clazz);
        }
    }
}